package sharemem

import (
	"encoding/json"
	"server_cluster/common/protoc/pb"
)

type UserWeapon struct {
	WeaponList [USER_WEAPON]Weapon // 武器列表
	//weaponMap            *hashmap.HashMap[uint64, *Weapon] // 武器集合 在线数据
	LastComposeWeaponKey uint64
}

func (w UserWeapon) MarshalJSON() ([]byte, error) {
	dbUserWeapon := struct {
		WeaponList []Weapon // 武器列表
	}{}
	for _, weapon := range w.WeaponList {
		if !weapon.IsUse() {
			continue
		}
		dbUserWeapon.WeaponList = append(dbUserWeapon.WeaponList, weapon)
	}
	data, err := json.Marshal(dbUserWeapon)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (w *UserWeapon) UnmarshalJSON(data []byte) error {
	dbUserWeapon := struct {
		WeaponList []Weapon // 武器列表
	}{}
	err := json.Unmarshal(data, &dbUserWeapon)
	if err != nil {
		return err
	}
	for index, weapon := range dbUserWeapon.WeaponList {
		w.WeaponList[index] = weapon
	}
	return nil
}

func (w *UserWeapon) MemInit() {
	for i := 0; i < len(w.WeaponList); i++ {
		w.WeaponList[i].MemInit()
	}
	w.LastComposeWeaponKey = 0
}

type Weapon struct {
	WeaponKey uint64 // 武器唯一id
	ItemId    int32  // 道具id
	Level     int16  // 等级
	Exp       int32  // 经验
	Promote   int8   // 等阶
	Star      int8   // 星级
	RoleId    int32  // 角色id
	IsLock    bool   // 是否锁定
}

func (w *Weapon) MemInit() {
	w.WeaponKey = 0
	w.ItemId = 0
	w.Level = 0
	w.Exp = 0
	w.Promote = 0
	w.Star = 0
	w.RoleId = 0
	w.IsLock = false
}

func (w *Weapon) IsUse() bool {
	return w.WeaponKey != 0
}

func (u *User) PacketWeapon(weapon *Weapon) *pb.Weapon {
	return &pb.Weapon{
		WeaponKey: weapon.WeaponKey,
		ItemId:    weapon.ItemId,
		Level:     int32(weapon.Level),
		Exp:       weapon.Exp,
		Promote:   int32(weapon.Promote),
		Star:      int32(weapon.Star),
		RoleId:    weapon.RoleId,
		IsLock:    weapon.IsLock,
	}
}

func (u *User) GetEmptyWeapon() *Weapon {
	for i := 0; i < len(u.UserWeapon.WeaponList); i++ {
		weapon := &(u.UserWeapon.WeaponList[i])
		if !weapon.IsUse() {
			return weapon
		}
	}
	return nil
}

func (u *User) AddNewWeapon(weapon *Weapon) {
	u.AddWeapon2Map(weapon.WeaponKey, weapon)
}

func (u *User) RemoveWeapon(weapon *Weapon) {
	u.DeleteWeapon(weapon.WeaponKey)
	weapon.MemInit()
}

func (u *User) GetWeaponRemainCellNum() int32 {
	return int32(USER_WEAPON - u.GetWeaponMapLen())
}

func (u *User) PackUserWeaponAll(rsp *pb.SC_Fetch) {
	rsp.WeaponList = make([]*pb.Weapon, 0, u.GetWeaponMapLen())
	for _, weapon := range u.GetWeaponMap() {
		rsp.WeaponList = append(rsp.WeaponList, u.PacketWeapon(weapon))
	}
}

func (u *User) SetLastComposeWeaponKey(key uint64) { u.UserWeapon.LastComposeWeaponKey = key }
func (u *User) GetLastComposeWeaponKey() uint64    { return u.UserWeapon.LastComposeWeaponKey }
